package com.cards_game.simple_ddz.service.impl;

import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
 
import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.cards_game.simple_ddz.bean.PlayerBean;
import com.cards_game.simple_ddz.common.AllPrimaryContainer;
import com.cards_game.simple_ddz.common.GameProgressEnum;
import com.cards_game.simple_ddz.common.RoomBean;
import com.cards_game.simple_ddz.component.InAndOutRoom;
import com.cards_game.simple_ddz.service.EnterGameServic;

/**
 * @author 郭国辉
 * 
 *     2017年6月22日下午5:20:26
 */
@Service
public class EnterGameServiceImpl implements EnterGameServic {
	private ConcurrentHashMap<Integer, RoomBean> allRoomMap = AllPrimaryContainer.getAllPrimaryContainer().getAllRoomMap();
//	private ConcurrentSkipListSet<RoomBean> notFullRooms = AllPrimaryContainer.getAllPrimaryContainer().getNotFullRooms();
//	@Resource
//	private InAndOutRoom iaor;
	
	/**
	 * @param userId
	 * @param roomId
	 * @return
	 */
	@Override
	public boolean enterGameRoom(int userId, String roomId) {
		boolean allotSucceed = false;
		RoomBean room=allRoomMap.get(roomId);
		PlayerBean player=new PlayerBean();
		player.setId(userId);
		allotSucceed = InAndOutRoom.accessRoom(player, room);
		return allotSucceed;
	}
	/**
	 * @param userId
	 * @return
	 */
	@Override
	public RoomBean quickGame(int userId) {
		RoomBean rb= InAndOutRoom.intoRoom(userId);
		allReady(rb.getId());
		return rb;
	}
	/**
	 * 判断是否所有人已准备
	 * @param roomId
	 * @param userId
	 * @return
	 */
	@Override
	public boolean allReady(int roomId) {
		boolean res=true;
		RoomBean room=allRoomMap.get(roomId);
		if(room.getGpe()==GameProgressEnum.ALL_READY){
			return res;
		}
		Vector<PlayerBean> vec = room.getPlayerList();
		if (vec != null && vec.size() != 0) {
			for (PlayerBean pb : vec) {
				if (!pb.isReady()) {
					res=false;
					break;
				}
			}
		}
		if(res&&room.getGpe().beforeTheFlowNode(GameProgressEnum.ALL_READY)){
			room.setGpe(GameProgressEnum.ALL_READY);
		}
		return res;
	}
	/**
	 * 玩家准备游戏
	 * @param roomId
	 * @param userId
	 */
	@Override
	public void ready(String roomId, String userId) {
		Vector<PlayerBean> vec = allRoomMap.get(roomId).getPlayerList();
		if (vec != null && vec.size() != 0) {
			for (PlayerBean pb : vec) {
				if (pb.getId() == Integer.parseInt(userId)) {
					pb.setReady(true);
					break;
				}
			}
		}
	}
}
